import { parse as parseErrorStack } from 'error-stack-parser'
import { StackFrame } from './stack-types'
import { AwsConfigGenerator } from './aws-config'

/**
 * 智能诊断与修复引擎
 * 集成Sentry错误分析和AWS配置生成
 */
export class DiagnosticEngine {
  private awsGenerator = new AwsConfigGenerator()

  /**
   * 分析错误堆栈并提供修复建议
   * @param stacktrace 错误堆栈
   * @returns 修复建议数组
   */
  async analyzeError(stacktrace: string): Promise<Solution[]> {
    const frames = await this.parseStacktrace(stacktrace)
    const solutions: Solution[] = []

    // 常见错误模式匹配
    if (this.isUnhandledPromise(frames)) {
      solutions.push({
        type: 'code-fix',
        description: '未处理的Promise拒绝',
        solution: '添加.catch()处理或使用try/catch包裹await调用',
        confidence: 0.9
      })
    }

    if (this.isMemoryLeak(frames)) {
      solutions.push({
        type: 'optimization',
        description: '潜在内存泄漏',
        solution: '检查事件监听器和闭包引用，使用内存分析工具确认',
        confidence: 0.7
      })
    }

    return solutions
  }

  /**
   * 生成基础设施配置
   * @param requirements 业务需求
   * @returns 生成的配置文件
   */
  async generateConfig(requirements: InfrastructureRequirements): Promise<string> {
    return this.awsGenerator.generate(requirements)
  }

  private async parseStacktrace(stacktrace: string): Promise<StackFrame[]> {
    try {
      return parseErrorStack(new Error(stacktrace))
    } catch (error) {
      console.error('解析堆栈跟踪失败:', error)
      return []
    }
  }

  private isUnhandledPromise(frames: StackFrame[]): boolean {
    return frames.some(f => 
      f.functionName?.includes('Promise') && 
      !f.functionName?.includes('catch')
    )
  }

  private isMemoryLeak(frames: StackFrame[]): boolean {
    return frames.some(f => 
      f.fileName?.includes('event-emitter') ||
      f.functionName?.includes('addListener')
    )
  }
}

interface Solution {
  type: 'code-fix' | 'optimization' | 'configuration'
  description: string
  solution: string
  confidence: number
}

interface InfrastructureRequirements {
  scalability: 'low' | 'medium' | 'high'
  availability: number // 0-99.999
  securityLevel: 'basic' | 'enterprise'
  region: string
}

class AwsConfigGenerator {
  generate(requirements: InfrastructureRequirements): string {
    // 简化的AWS配置生成逻辑
    return JSON.stringify({
      Resources: {
        EC2Instance: {
          Type: "AWS::EC2::Instance",
          Properties: {
            InstanceType: this.getInstanceType(requirements.scalability),
            AvailabilityZone: `${requirements.region}a`
          }
        }
      }
    }, null, 2)
  }

  private getInstanceType(level: 'low' | 'medium' | 'high'): string {
    switch(level) {
      case 'low': return 't3.micro'
      case 'medium': return 'm5.large' 
      case 'high': return 'c5.2xlarge'
    }
  }
}